import { login as loginApi } from '@/api/login'
import router from '@/router'
// 引入登录时设置时间
import { setTokenTime } from '@/utils/utils'

export default {
  namespaced: true,
  state () {
    return {
      token: localStorage.getItem('token') || '',
      toggleSide: false,
      lang: localStorage.getItem('lang') || 'zh'
    }
  },
  mutations: {
    setToken (state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    // 伸缩侧边栏
    setToggle (state) {
      state.toggleSide = !state.toggleSide
    },
    // 改变语言
    changeLang (state, lang) {
      state.lang = lang
    }
  },
  actions: {
    // 登录
    login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginApi(userInfo).then(res => {
          setTokenTime()
          commit('setToken', res.token)
          router.replace('/')
          resolve()
        })
      }).catch(err => {
        return (err)
      })
    },
    // 时间失效后自动退出登录
    loginOut ({ commit }) {
      commit('setToken', '')
      localStorage.removeItem('token')
      router.replace('/login')
    }
  }
}
